package com.gopay.scheduler.job;

import com.gopay.common.constants.dic.GopayGlobalVariablesConstant;
import com.gopay.common.dss.tools.FuseTool;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.scheduler.GopayBaseJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

/**
 * Created by zhaojt on 2017/11/15.
 *
 * DTS自动补偿失败告警
 */
public class DtsCompFailAlarmJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "fuseTool")
    private FuseTool fuseTool;

    @Override
    protected void doJobInternal() {
        try {
            logger.info("DTS自动补偿失败告警任务...");

            int count = executeQuery();

            logger.info("queryCount = " + count);

            if (count > 0) {
                logger.error("触发阈值执行报警...");
                fuseTool.fuse(GopayGlobalVariablesConstant.DTS_COMP_FAIL_SWITCH, GopayGlobalVariablesConstant.DTS_COMP_FAIL_FUSE_MOBILE, 1);
            }

            logger.info("DTS自动补偿失败告警任务结束");

        }catch (Exception e){
            logger.error("DTS自动补偿失败告警任务异常", e);
        }


    }

    /**
     * 查询当天 原子动作表补偿7次 并且状态为非成功的记录条数
     * @return
     */
    private int executeQuery(){

        int count = commonQueryDAO.findCountBySql(buildSQL());

        return count;
    }

    private String buildSQL(){
        StringBuilder sql = new StringBuilder();
        sql.append(" select count(*) from dts_business_activity_log t ");
        sql.append(" where t.status = 30000 ");
        sql.append(" and t.create_time > (sysdate - 1) ");
        sql.append(" and t.create_time < sysdate - (3/24) ");

        return sql.toString();
    }


}
